package com.water.expert.extraction.controller;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.water.expert.extraction.repository.Extraction;
import com.water.expert.extraction.repository.ExtractionRepository;

@RestController
@RequestMapping("/extractions")
public class ExtractionController {
	@Autowired
	private ExtractionRepository extractionRepository;

	// 获取所有抽取记录
	@GetMapping
	public Iterable<Extraction> getAllExtractions() {
		return extractionRepository.findAll();
	}

	// 根据 ID 获取抽取记录
	@GetMapping("/{id}")
	public ResponseEntity<Extraction> getExtractionById(@PathVariable Long id) {
		return extractionRepository.findById(id).map(ResponseEntity::ok)
				.orElseGet(() -> ResponseEntity.notFound().build());
	}

	// 创建抽取记录
	@PostMapping
	public Extraction createExtraction(@RequestBody Extraction extraction) {
		extraction.setSelectionDateTime(LocalDateTime.now());
		return extractionRepository.save(extraction);
	}
	
	// 更新抽取记录
	@PutMapping("/{id}")
	public ResponseEntity<Extraction> updateExtraction(@PathVariable Long id,
			@RequestBody Extraction updatedExtraction) {
		return extractionRepository.findById(id).map(Extraction -> {
			updatedExtraction.setId(id);
			return ResponseEntity.ok(extractionRepository.save(updatedExtraction));
		}).orElseGet(() -> ResponseEntity.notFound().build());
	}

	// 删除抽取记录
	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteExtraction(@PathVariable Long id) {
		return extractionRepository.findById(id).map(extraction -> {
			extractionRepository.deleteById(id);
			return ResponseEntity.ok().<Void>build();
		}).orElseGet(() -> ResponseEntity.notFound().build());
	}
}
